<?php

/*
	Class: Commerce_Magento
		This abstract class sets up a SOAP connection to an instance of Magento.

	About: Author
		Rich Joslin

	About: License
		<http://communit.as/docs/license>
*/
abstract class Commerce_Db_Model_Magento extends Cts_Db_Table_Abstract {

	/* Group: Properties */

	public $_api_session_id;
	public $_customer_session_id;

	/* Group: Constructors */

	/*
		Constructor: __construct
			Sets up a SOAP object for communicating with a Magento API.
			Sets up a cache object for all models to use.
	*/
	function __construct($customer_session_id = null) { // $checkout_session_id
		if (!is_null($customer_session_id)) {
			$this->_customer_session_id = $customer_session_id;
		}
		$cache_instance = new Commerce_Cache();
		$this->cache = $cache_instance->factory;
	}

	protected function initSoap() {
		if (!isset($this->client)) {
			$wsdl_url = Cts_Registry::get('magento_soap_wsdl_url','commerce');
			if (!is_null($this->_customer_session_id)) {
				$wsdl_url .= '&SID='.$this->_customer_session_id;
			}
			$api_user = Cts_Registry::get('magento_soap_username','commerce');
			$api_pass = Cts_Registry::get('magento_soap_password','commerce'); // Magento calls it "API Key"
			$this->client = new SoapClient($wsdl_url);
			// TODO : if the SOAP login fails, show a message or something and email an administrator
			// nobody should be able to use Magento functions if the Magento app is unreachable
			try {
				$this->_api_session_id = $this->client->login($api_user, $api_pass);
			} catch (Exception $e) {
				throw($e);
			}
		}
	}

}
